<template>
  <el-card>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="排班列表" name="list">
        <div class="toolbar">
          <el-form :inline="true" :model="searchForm" size="small">
            <el-form-item label="客服姓名">
              <el-select v-model="searchForm.staffName" placeholder="请选择客服" clearable style="width: 180px;">
                <el-option v-for="staff in staffList" :key="staff" :label="staff" :value="staff"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班次">
              <el-select v-model="searchForm.shift" placeholder="请选择班次" clearable style="width: 180px;">
                <el-option v-for="shift in shiftTypes" :key="shift.id" :label="shift.name" :value="shift.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-button type="primary" @click="handleAddSchedule" size="small">新增排班</el-button>
            <el-button type="danger" @click="handleBatchDelete" size="small" :disabled="!selectedSchedules.length">批量删除</el-button>
            <el-button type="success" @click="handleBatchUpdateStatus('published')" size="small" :disabled="!selectedSchedules.length">批量发布</el-button>
            <el-button type="warning" @click="handleBatchUpdateStatus('draft')" size="small" :disabled="!selectedSchedules.length">批量撤回</el-button>
            <el-button type="info" @click="handleExport" size="small">导出</el-button>
          </div>
        </div>
        <el-table :data="pagedSchedules" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="staffName" label="客服姓名"></el-table-column>
            <el-table-column prop="shift" label="班次">
                <template #default="scope">
                    <el-tag :color="getShiftColor(scope.row.shift)" style="color: white;">{{ scope.row.shift }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="dateRange" label="排班日期范围"></el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="160"></el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-tag :type="scope.row.type" :effect="scope.row.status === 'published' ? 'dark' : 'light'">
                        {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button size="small" @click="handleEditSchedule(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDeleteSchedule(scope.row)">删除</el-button>
                    <el-button size="small" type="info" @click="handleViewLogs(scope.row)">日志</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 16px; justify-content: flex-end;"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredSchedules.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </el-tab-pane>
      <el-tab-pane label="班次管理" name="shifts">
        <div class="toolbar">
          <el-button type="primary" @click="handleAddShift">新增班次</el-button>
        </div>
        <el-table :data="shifts" border stripe>
          <el-table-column prop="name" label="班次名称"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="120"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="120"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="handleEditShift(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteShift(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="scheduleDialogVisible" :title="isEditSchedule ? '编辑排班' : '新增排班'" width="500px">
      <el-form :model="scheduleForm" label-width="80px">
        <el-form-item label="客服">
          <el-select v-model="scheduleForm.staffName" placeholder="请选择客服">
            <el-option v-for="staff in staffList" :key="staff" :label="staff" :value="staff"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班次">
          <el-select v-model="scheduleForm.shift" placeholder="请选择班次">
            <el-option v-for="shift in shiftTypes" :key="shift.id" :label="shift.name" :value="shift.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="scheduleForm.status"
            active-text="发布"
            inactive-text="草稿"
            active-value="published"
            inactive-value="draft"
          ></el-switch>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="scheduleForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="isEditSchedule"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button v-if="isEditSchedule" type="danger" @click="handleDeleteSchedule" style="float: left;">删除</el-button>
        <el-button @click="scheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitSchedule">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="shiftDialogVisible" :title="isEditShift ? '编辑班次' : '新增班次'" width="500px">
      <el-form :model="shiftForm" label-width="100px">
        <el-form-item label="班次名称">
          <el-input v-model="shiftForm.name"></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-time-select v-model="shiftForm.startTime" start="00:00" step="00:30" end="23:30" placeholder="选择时间"></el-time-select>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-time-select v-model="shiftForm.endTime" start="00:00" step="00:30" end="23:30" placeholder="选择时间"></el-time-select>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="shiftForm.color"></el-color-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shiftDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitShift">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="logDialogVisible" title="排班日志" width="600px">
        <el-timeline>
            <el-timeline-item v-for="log in currentScheduleLogs" :key="log.timestamp" :timestamp="log.timestamp">
                <strong>{{ log.action }}</strong> by {{ log.operator }}
                <p>{{ log.details }}</p>
            </el-timeline-item>
        </el-timeline>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessageBox, ElNotification } from 'element-plus';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
import * as XLSX from 'xlsx';
dayjs.extend(isBetween);

const activeTab = ref('list');
const staffList = ref(['客服A', '客服B', '客服C', '客服D']);

// 班次类型
const shiftTypes = ref([
  { id: 1, name: '早班', startTime: '09:00', endTime: '18:00', color: '#409EFF' },
  { id: 2, name: '晚班', startTime: '18:00', endTime: '24:00', color: '#E6A23C' },
  { id: 3, name: '休息', startTime: '', endTime: '', color: '#909399' },
]);

// --- 搜索和分页 ---
const searchForm = ref({
  staffName: '',
  shift: '',
  dateRange: [],
});
const currentPage = ref(1);
const pageSize = ref(10);
const selectedSchedules = ref<any[]>([]);

// --- 班次管理 ---
const shifts = ref([
  { id: 1, name: '早班', startTime: '09:00', endTime: '18:00' },
  { id: 2, name: '晚班', startTime: '18:00', endTime: '24:00' },
  { id: 3, name: '休息', startTime: '', endTime: '' },
]);
const shiftDialogVisible = ref(false);
const isEditShift = ref(false);
const shiftForm = ref({
  id: -1,
  name: '',
  startTime: '',
  endTime: '',
  color: '#409EFF'
});

const handleAddShift = () => {
  isEditShift.value = false;
  shiftForm.value = { id: -1, name: '', startTime: '', endTime: '', color: '#409EFF' };
  shiftDialogVisible.value = true;
};

const handleEditShift = (shift: any) => {
  isEditShift.value = true;
  shiftForm.value = { ...shift };
  shiftDialogVisible.value = true;
};

const handleDeleteShift = (shift: any) => {
  ElMessageBox.confirm(`确定要删除班次【${shift.name}】吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    shifts.value = shifts.value.filter(s => s.id !== shift.id);
  });
};

const handleSubmitShift = () => {
  if (isEditShift.value) {
    const index = shifts.value.findIndex(s => s.id === shiftForm.value.id);
    if (index !== -1) {
      shifts.value[index] = { ...shiftForm.value };
    }
  } else {
    shifts.value.push({ ...shiftForm.value, id: Date.now() });
  }
  shiftDialogVisible.value = false;
};


// --- 排班日志 ---
const scheduleLogs = ref<any[]>([]);
const logDialogVisible = ref(false);
const currentScheduleLogs = ref<any[]>([]);

const addLog = (scheduleId: number, action: string, details: string) => {
    scheduleLogs.value.push({
        scheduleId,
        action,
        details,
        operator: '当前用户', // 模拟当前登录用户
        timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss')
    });
};

const handleViewLogs = (row: any) => {
    currentScheduleLogs.value = scheduleLogs.value.filter(log => log.scheduleId === row.id).sort((a, b) => dayjs(b.timestamp).valueOf() - dayjs(a.timestamp).valueOf());
    logDialogVisible.value = true;
};


// --- 通知提醒 ---
const sendNotification = (staffName: string, message: string) => {
    ElNotification({
        title: '通知提醒',
        message: `已向【${staffName}】发送通知：${message}`,
        type: 'success',
    });
};


// --- 排班列表 ---
const schedules = ref(Array.from({ length: 20 }, (_, i) => {
    const staffIndex = i % staffList.value.length;
    const shiftIndex = i % shiftTypes.value.length;
    const startDate = dayjs().add(i * 3, 'day');
    const endDate = startDate.add(Math.floor(Math.random() * 5) + 1, 'day');
    return {
        id: i + 1,
        staffName: staffList.value[staffIndex],
        shift: shiftTypes.value[shiftIndex].name,
        startDate: startDate.format('YYYY-MM-DD'),
        endDate: endDate.format('YYYY-MM-DD'),
        dateRange: `${startDate.format('YYYY-MM-DD')} ~ ${endDate.format('YYYY-MM-DD')}`,
        createdAt: dayjs().subtract(Math.floor(Math.random() * 10), 'day').format('YYYY-MM-DD HH:mm:ss'),
        type: ['success', 'warning', 'info'][shiftIndex % 3],
        status: i % 4 === 0 ? 'draft' : 'published'
    };
}));
// 初始化一些日志
schedules.value.forEach(s => addLog(s.id, '创建排班', `系统初始化创建`));


const getShiftColor = (shiftName: string) => {
    const shift = shiftTypes.value.find(s => s.name === shiftName);
    return shift ? shift.color : '#909399';
};

const filteredSchedules = computed(() => {
    let data = [...schedules.value];
    if (searchForm.value.staffName) {
        data = data.filter(s => s.staffName.includes(searchForm.value.staffName));
    }
    if (searchForm.value.shift) {
        data = data.filter(s => s.shift === searchForm.value.shift);
    }
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
        const [searchStart, searchEnd] = searchForm.value.dateRange.map(d => dayjs(d));
        data = data.filter(s => {
            const scheduleStart = dayjs(s.startDate);
            const scheduleEnd = dayjs(s.endDate);
            // 检查排班范围与搜索范围是否有交集
            return searchStart.isBefore(scheduleEnd.add(1, 'day')) && searchEnd.isAfter(scheduleStart.subtract(1, 'day'));
        });
    }
    return data.sort((a, b) => dayjs(b.startDate).valueOf() - dayjs(a.startDate).valueOf());
});

const pagedSchedules = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredSchedules.value.slice(start, end);
});

const handleSearch = () => {
    currentPage.value = 1;
};

const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
    currentPage.value = val;
};

const handleSelectionChange = (val: any[]) => {
    selectedSchedules.value = val;
};


const scheduleDialogVisible = ref(false);
const isEditSchedule = ref(false);
const scheduleForm = ref({
  id: -1,
  staffName: '',
  shift: '',
  dateRange: [] as string[],
  type: 'primary',
  status: 'draft'
});

const handleAddSchedule = () => {
  isEditSchedule.value = false;
  scheduleForm.value = {
    id: -1,
    staffName: '',
    shift: '',
    dateRange: [],
    type: 'primary',
    status: 'draft'
  };
  scheduleDialogVisible.value = true;
};

const handleEditSchedule = (schedule: any) => {
  isEditSchedule.value = true;
  scheduleForm.value = { ...schedule, dateRange: [schedule.startDate, schedule.endDate] };
  scheduleDialogVisible.value = true;
};

const handleDeleteSchedule = (row: any) => {
  ElMessageBox.confirm(`确定要删除【${row.staffName}】在【${row.dateRange}】的排班吗?`, '提示', {
    type: 'warning',
  }).then(() => {
    addLog(row.id, '删除排班', `删除了【${row.staffName}】在【${row.dateRange}】的【${row.shift}】`);
    schedules.value = schedules.value.filter(s => s.id !== row.id);
    sendNotification(row.staffName, `您在【${row.dateRange}】的排班已被取消。`);
  });
};

const handleSubmitSchedule = () => {
  const shiftTypeMap: { [key: string]: string } = {
    '早班': 'success',
    '晚班': 'warning',
    '休息': 'danger'
  };
  const type = shiftTypeMap[scheduleForm.value.shift] || 'primary';

  if (isEditSchedule.value) {
    const index = schedules.value.findIndex(s => s.id === scheduleForm.value.id);
    if (index !== -1) {
      const oldSchedule = schedules.value[index];
      const newSchedule = {
        id: scheduleForm.value.id,
        staffName: scheduleForm.value.staffName,
        shift: scheduleForm.value.shift,
        startDate: scheduleForm.value.dateRange[0],
        endDate: scheduleForm.value.dateRange[1],
        dateRange: scheduleForm.value.dateRange.join(' ~ '),
        createdAt: oldSchedule.createdAt,
        type: type,
        status: scheduleForm.value.status,
      };

      // 生成变更详情
      const changes = [];
      if (oldSchedule.staffName !== newSchedule.staffName) changes.push(`客服由【${oldSchedule.staffName}】变更为【${newSchedule.staffName}】`);
      if (oldSchedule.shift !== newSchedule.shift) changes.push(`班次由【${oldSchedule.shift}】变更为【${newSchedule.shift}】`);
      if (oldSchedule.status !== newSchedule.status) changes.push(`状态由【${oldSchedule.status}】变更为【${newSchedule.status}】`);
      
      if (changes.length > 0) {
        addLog(newSchedule.id, '编辑排班', changes.join('；'));
        sendNotification(newSchedule.staffName, `您在【${newSchedule.dateRange}】的排班已更新。`);
      }
      schedules.value[index] = newSchedule;
    }
  } else {
    // 排班冲突校验
    const [start, end] = scheduleForm.value.dateRange;
    const existing = schedules.value.find(s => {
        const scheduleStart = dayjs(s.startDate);
        const scheduleEnd = dayjs(s.endDate);
        const newStart = dayjs(start);
        const newEnd = dayjs(end);
        return s.staffName === scheduleForm.value.staffName && newStart.isBefore(scheduleEnd.add(1, 'day')) && newEnd.isAfter(scheduleStart.subtract(1, 'day'));
    });
    if (existing) {
        ElMessageBox.alert(`客服【${scheduleForm.value.staffName}】在此时间段内已有排班【${existing.dateRange}】，请勿重复添加。`, '排班冲突');
        return;
    }

    const newEntry = {
        id: Date.now(),
        staffName: scheduleForm.value.staffName,
        shift: scheduleForm.value.shift,
        startDate: start,
        endDate: end,
        dateRange: `${start} ~ ${end}`,
        createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        type: type,
        status: scheduleForm.value.status,
    };
    addLog(newEntry.id, '创建排班', `为【${newEntry.staffName}】创建了【${newEntry.dateRange}】的【${newEntry.shift}】`);
    schedules.value = [...schedules.value, newEntry];
    sendNotification(scheduleForm.value.staffName, `您已被安排新的排班，从【${start}】到【${end}】。`);
  }
  scheduleDialogVisible.value = false;
};

const handleBatchDelete = () => {
    ElMessageBox.confirm(`确定要删除选中的 ${selectedSchedules.value.length} 条排班吗？`, '提示', {
        type: 'warning',
    }).then(() => {
        const idsToDelete = selectedSchedules.value.map(s => s.id);
        selectedSchedules.value.forEach(s => {
            addLog(s.id, '批量删除排班', `删除了【${s.staffName}】在【${s.dateRange}】的【${s.shift}】`);
            sendNotification(s.staffName, `您在【${s.dateRange}】的排班已被取消。`);
        });
        schedules.value = schedules.value.filter(s => !idsToDelete.includes(s.id));
        ElMessageBox.alert('批量删除成功');
    });
};

const handleBatchUpdateStatus = (status: 'published' | 'draft') => {
    const statusText = status === 'published' ? '发布' : '撤回';
    ElMessageBox.confirm(`确定要批量${statusText}选中的 ${selectedSchedules.value.length} 条排班吗？`, '提示', {
        type: 'warning',
    }).then(() => {
        const idsToUpdate = selectedSchedules.value.map(s => s.id);
        schedules.value.forEach(s => {
            if (idsToUpdate.includes(s.id)) {
                if(s.status !== status) {
                    addLog(s.id, `批量${statusText}排班`, `将【${s.staffName}】在【${s.dateRange}】的排班状态变更为【${status}】`);
                    sendNotification(s.staffName, `您在【${s.dateRange}】的排班状态已更新为【${statusText}】。`);
                    s.status = status;
                }
            }
        });
        ElMessageBox.alert(`批量${statusText}成功`);
    });
};

const handleExport = () => {
    const dataToExport = selectedSchedules.value.length ? selectedSchedules.value : filteredSchedules.value;
    const worksheet = XLSX.utils.json_to_sheet(dataToExport);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '排班数据');
    XLSX.writeFile(workbook, '排班数据.xlsx');
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
</style> 